<?php
/**
 * 对Zend/Db.php 的factory方法进行的简单封装
 * @return Zend_Db_Adapter [<description>]
 * 主要使用场景是：在控制器内不想实例化model来进行数据库查询
 * 例如 Base_Db::getInstance("writeDb")->fetchALl(sql语句)
 */
class Model_Db {
	/**
	 * 链接数据库
	 * @param  [type] $connectionName database.ini中每个数据库链接的section名称,不传值使用配置的默认链接
	 * @return Zend_Db_Adapter_Abstract
	 */
	public static function getInstance($connectionName = "") {
		if ($connectionName === "") {
			try {
				$defaultSectionConfig = Helper_Config::get('database', 'default', 'connection', null, true);
				$connectionName = $defaultSectionConfig['section'];
			} catch (Exception $e) {
				throw new Exception("请指定数据链接名称或配置合法的默认链接");
			}
		}

		$registry = Zend_Registry::getInstance();
		if (isset($registry['_dbConnections']) && isset($registry['_dbConnections'][$connectionName]) && $registry['_dbConnections'][$connectionName] instanceof Zend_Db_Adapter_Abstract) {
			return $registry['_dbConnections'][$connectionName];
		}
		$dbConfig = Helper_Config::get('database', $connectionName);
		$db = Zend_Db::factory($dbConfig['database']['adapter'], $dbConfig['database']['params']);
		$registry['_dbConnections'][$connectionName] = $db;
		return $db;
	}
}